package servlet.controller;

import cn.dsna.util.images.ValidateCode;
import common.Const;
import common.ResponseCode;
import entity.User;
import service.UserService;
import service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * User: key
 * ClassName:SystemController
 * Date: 2023/5/5
 * Time: 20:24
 * description:
 */
@WebServlet("/sys")
public class SystemController extends HttpServlet {
    private UserService us = new UserServiceImpl();

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String method = req.getParameter("method");
        if(method == null){
            method = "login";
        }
        switch (method){
            case "getCode":
                getCode(req,resp);
                break;
            case "checkCode":
                checkCode(req,resp);
                break;
            case "logout":
                logout(req,resp);
                break;
            case "login":
                login(req,resp);
                break;
            default:
                req.setAttribute("msg","没有这个页面");
                req.getRequestDispatcher("message.jsp").forward(req,resp);
        }
    }

    private void login(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        String name = req.getParameter("name");
        String password = req.getParameter("password");
        User user = us.doLogin(name,password);
        if(user != null){
            req.getSession().setAttribute(Const.LOGIN_INFO,user);
            resp.sendRedirect("/book?method=getByPage&pageNum=1");
        }else {
            req.setAttribute("msg","登陆失败");
            req.getRequestDispatcher("message.jsp").forward(req,resp);
        }
    }

    private void logout(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        req.getSession().invalidate();
        resp.sendRedirect("/login.jsp");
    }

    private void checkCode(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String code = req.getParameter("code");
        String valiCode = (String) req.getSession().getAttribute(Const.VALI_CODE);
        if(valiCode.equalsIgnoreCase(code)){
            resp.getWriter().println(ResponseCode.SUCCESS.getCode());
        }else {
            resp.getWriter().println(ResponseCode.FAIL.getCode());
        }
    }

    private void getCode(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        ValidateCode vc = new ValidateCode(120,40,4,20);
        String code = vc.getCode();
        System.out.println(code);
        req.getSession().setAttribute(Const.VALI_CODE,code);
        vc.write(resp.getOutputStream());
    }
}
